package com.zhousb.deviceManager.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.zhousb.deviceManager.mapper.ImNoticeMapper;
import com.zhousb.deviceManager.model.entity.ImNotice;
import com.zhousb.deviceManager.model.enums.NoticeTypeEnum;
import com.zhousb.deviceManager.model.so.NoticeSo;
import com.zhousb.deviceManager.security.JwtUser;
import com.zhousb.deviceManager.service.NoticeService;
import com.zhousb.deviceManager.utils.AuthUtils;
import com.zhousb.deviceManager.utils.IdGenerator;
import com.zhousb.deviceManager.ws.WebSocketServer;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ZhouShenBin
 * @date 2024/7/11 10:36
 * @description
 */

@Service
@Slf4j
public class NoticeServiceImpl implements NoticeService {

    @Resource
    private AuthUtils authUtils;
    @Resource
    private ImNoticeMapper noticeMapper;

    @Override
    public IPage<ImNotice> page(Page<ImNotice> page, NoticeSo so) {
        Long userId = authUtils.getUser().getUserId();
        LambdaQueryWrapper<ImNotice> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasText(so.getStatus())) {
            queryWrapper.eq(ImNotice::getStatus, Integer.parseInt(so.getStatus()));
        }
        queryWrapper.like(ImNotice::getTargetUserId, userId);
        queryWrapper.orderByAsc(ImNotice::getStatus).orderByDesc(ImNotice::getCreateTime);

        return noticeMapper.selectPage(page, queryWrapper);
    }

    @Override
    public List<ImNotice> list() {
        Long userId = authUtils.getUser().getUserId();
        LambdaQueryWrapper<ImNotice> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(ImNotice::getTargetUserId, userId);
        queryWrapper.orderByAsc(ImNotice::getStatus).orderByDesc(ImNotice::getCreateTime);

        return noticeMapper.selectList(queryWrapper);
    }

    @Override
    public boolean read(String id) {
        ImNotice notice = new ImNotice();
        notice.setId(Long.parseLong(id));
        notice.setStatus(1);
        noticeMapper.updateById(notice);
        return true;
    }

    @Override
    public boolean readAll() {
        JwtUser jwtUser = authUtils.getUser();
        LambdaUpdateWrapper<ImNotice> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(ImNotice::getStatus, 1).eq(ImNotice::getTargetUserId, jwtUser.getUserId()).eq(ImNotice::getStatus, 0);
        noticeMapper.update(updateWrapper);
        return true;
    }

    @Resource
    private WebSocketServer webSocketServer;

    @Override
    public void createNotice(NoticeTypeEnum type, String content, Long orderId, List<Long> targetUserIds) {
        try {
            ImNotice notice = new ImNotice();

            notice.setType(type.getName());
            notice.setContent(content);
            notice.setColor(type.getColor());
            if (orderId != null) {
                notice.setOrderId(orderId);
            }
            if (targetUserIds != null && !targetUserIds.isEmpty()) {
                targetUserIds.forEach(id -> {
                    notice.setId(IdGenerator.nextId());
                    notice.setTargetUserId(id.toString());
                    noticeMapper.insert(notice);
                });
            }
            if (targetUserIds != null && !targetUserIds.isEmpty()) {
                webSocketServer.sendMoreMessage(targetUserIds.toArray(new Long[0]), JSONUtil.toJsonStr(notice));
            }
        }catch (Exception e){
            log.error("创建消息报错");
            e.printStackTrace();
        }
    }
}
